//
//  AddRecordViewController.m
//  YunGui
//
//  Created by wmm on 16/4/6.
//  Copyright © 2016年 hanen. All rights reserved.
//

#import "AddRecordViewController.h"
#import "QBImagePickerController.h"
#import "PictureSelectView.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import "CameraViewController.h"
//#import "DBCameraView.h"

#define LocationTimeout 3  //   定位超时时间，可修改，最小2s
#define ReGeocodeTimeout 3 //   逆地理请求超时时间，可修改，最小2s

@interface AddRecordViewController ()<QBImagePickerControllerDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,PictureSelectViewDelegate,AMapLocationManagerDelegate>
{
    UIScrollView * scrollView;
    
    PictureSelectView *picVew;
    NSMutableArray  *_choosePicDataArray;
    NSMutableArray  *_cameraPicArray;
    NSMutableArray *pic;
    
    NSString *gps;
    NSString *gps_address;
}

@property(nonatomic,strong)UITextField  *nameTF;
@property(nonatomic,strong)UITextField  *telTF;
@property(nonatomic,strong)UITextView  *visitTV;

@property (nonatomic, strong) AMapLocationManager *locationManager;

@property (nonatomic, copy) AMapLocatingCompletionBlock completionBlock;

@end

@implementation AddRecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = GrayBackColor;
    self.navigationItem.hidesBackButton = YES;
    [ViewTool setNavigationBar:self.navigationController.navigationBar];
    self.navigationItem.title = @"添加记录";
    self.navigationItem.leftBarButtonItem = [ViewTool getBarButtonItemWithTarget:self WithString:@"back" WithAction:@selector(goToBack)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(commitClick:)];
    
    scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64)];
    scrollView.showsVerticalScrollIndicator=NO;
    [self.view addSubview:scrollView];
    gps_address = @"无定位信息";
    gps = [NSString stringWithFormat:@"0,0"];
    
    [self initListView];
}

- (void)goToBack{
    [self cleanUpAction];
    self.completionBlock = nil;
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)uploadImage:(NSData *)imgData success:(SuccessBlock)successBlock fail:(FailBlock)faileBlock{
    [DataTool uploadPic:imgData success:^(id data) {
        NSLog(@"%@",data);
        NSString *status = [(NSDictionary *)data objectForKey:@"status"];
        if ([status isEqualToString:@"SUCCESS"]) {
            NSString *picUrl = [[(NSDictionary *)data objectForKey:@"data"] objectForKey:@"pic"];
            [pic addObject:picUrl];
            successBlock(data);
        }else{
            NSString *msg = [(NSDictionary *)data objectForKey:@"msg"];
            [SVProgressHUD dismiss];
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(commitClick:)];
            [Tools showMessage:msg view:self];
        }
    } fail:^(NSError *error) {
        [SVProgressHUD dismiss];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(commitClick:)];
        [Tools showMessage:@"图片上传失败" view:self];
    }];
}


- (void)addRecord{
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
    [dictionary setObject:@"app.visit.store.record" forKey:@"method"];
    NSNumber *visitId = [NSNumber numberWithInt:_model.visit_id];
    
    [dictionary setObject:visitId forKey:@"id"];
    [dictionary setObject:gps forKey:@"gps"];
    [dictionary setObject:gps_address forKey:@"gps_address"];

    [dictionary setObject:_visitTV.text forKey:@"desc"];
    [dictionary setObject:_nameTF.text forKey:@"contact"];
    [dictionary setObject:_telTF.text forKey:@"tel"];
    
    NSLog(@"%@",[pic componentsJoinedByString:@","]);
    NSString *picStr = [NSString stringWithFormat:@"%@",[pic componentsJoinedByString:@","]];
    [dictionary setObject:picStr forKey:@"image"];
   
    [DataTool postWithUrl:HEAD_URL parameters:[DataTool addSignToDic:dictionary] success:^(id data) {
        [SVProgressHUD dismiss];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(commitClick:)];
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSString *status = [(NSDictionary *)jsonDic objectForKey:@"status"];
        NSLog(@"返回 %@",jsonDic);
        if ([status isEqualToString:@"SUCCESS"]) {
            
            [SVProgressHUD showSuccessWithStatus:@"新建成功"];
            [_delegate passValue:@"SUCCESS"];
            [self goToBack];
        }else{
            NSString *code = [(NSDictionary *)jsonDic objectForKey:@"code"];
            NSString *msg = [(NSDictionary *)jsonDic objectForKey:@"msg"];
            NSLog(@"%@%@%@",status,code,msg);
            [Tools showMessage:msg view:self];
        }
        
    } fail:^(NSError *error) {
        [SVProgressHUD dismiss];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(commitClick:)];
        NSLog(@"error:%@",error);
        [Tools showMessage:@"新建失败" view:self];
    }];
}

#pragma mark --定位的方法
- (void)localization
{
    if ([CLLocationManager locationServicesEnabled] &&
        ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized
         || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined)) {
            [SVProgressHUD show];
            self.navigationItem.rightBarButtonItem=nil;
            //定位功能可用，开始定位
            [self initCompleteBlock];
            [self configLocationManager];
            [self reGeocodeAction];
        }
    else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied){
        [Tools showMessage:@"提示:您未开启定位，请先开启定位。" view:self];
    }
}

-(void)uploadImages{
    if (picVew.allPicArray.count == 1) {
        [self uploadImage:picVew.allPicArray[0] success:^(id data) {
            [self addRecord];
        } fail:^(NSError *error) {
            
        }];
    }else if (picVew.allPicArray.count == 2){
        [self uploadImage:picVew.allPicArray[0] success:^(id data) {
            [self uploadImage:picVew.allPicArray[1] success:^(id data1) {
                [self addRecord];
            } fail:^(NSError *error) {
                
            }];
        } fail:^(NSError *error) {
            
        }];
    }else if (picVew.allPicArray.count == 3){
        [self uploadImage:picVew.allPicArray[0] success:^(id data) {
            [self uploadImage:picVew.allPicArray[1] success:^(id data1) {
                [self uploadImage:picVew.allPicArray[2] success:^(id data2) {
                    [self addRecord];
                } fail:^(NSError *error) {
                    
                }];
            } fail:^(NSError *error) {
                
            }];
        } fail:^(NSError *error) {
            
        }];
    }
}


//提交
-(void)commitClick:(UIButton *)btn{
    pic = [NSMutableArray array];
    [_visitTV resignFirstResponder];
    if (_nameTF.text == nil | [_nameTF.text length] == 0 ){
        [self.view makeToast:@"请填写联系人"];
        return;
    }else if (_telTF.text == nil | [_telTF.text length] == 0 ){
        [self.view makeToast:@"请填写联系电话"];
        return;
    }else if (![JudgeNumber boolenPhone:_telTF.text]){
        [self.view makeToast:@"请填写正确的联系电话"];
        return;
    }else if (_visitTV.text == nil | [_visitTV.text length] == 0 ){
        [self.view makeToast:@"请填写拜访记录"];
        return;
    }else if ([_visitTV.text length] < 30 ){
        [self.view makeToast:@"拜访记录不少于30个字"];
        return;
    }else if (picVew.allPicArray.count == 0){
        [self.view makeToast:@"请上传照片"];
        return;
    }

    [self localization];
}

- (void)initListView{
    CGFloat startX = [UIView getWidth:20];
    CGFloat imgW = 20;
    CGFloat labX = startX + imgW +15;
    CGFloat labH = 40;
    CGFloat labY = 10;
    CGFloat height = labH - 2*labY;
    CGFloat grayH = 15;
    CGFloat labW  = 80;
    CGFloat tfX = labX + labW +[UIView getWidth:5];
    CGFloat tfW = kScreenWidth - tfX;
    
    UIView *sectionView = [ViewTool getLineViewWith:CGRectMake(0, 0, kScreenWidth, grayH) withBackgroudColor:GrayBackColor];
    [scrollView addSubview:sectionView];
    UIView *line = [self getLineWith:CGRectMake(0, sectionView.maxY - 1, kScreenWidth, 1)];
    [scrollView addSubview:line];
    
    UIView *bg = [[UIView alloc] initWithFrame:CGRectMake(0, sectionView.maxY, kScreenWidth, 200)];
    bg.backgroundColor = [UIColor whiteColor];
    [scrollView addSubview:bg];
    
    UIImageView *recordImg = [self imageWith:CGRectMake(startX, line.maxY + labY +1.5, imgW, imgW) withName:@"Btn_Normal_Baifangjilu.png"];
    [scrollView addSubview:recordImg];
    
    UILabel *infoLabel = [self getLabelWith:CGRectMake(labX, line.maxY + labY +1.5, labW, height) WithTitle:@"拜访信息" withColor:BLACKCOLOR];
    infoLabel.font = [ViewTool getFont:16.0f];
    [scrollView addSubview:infoLabel];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(infoLabel.x, infoLabel.maxY + labY+1.5 -1, kScreenWidth - infoLabel.x, 1)];
    lineView.backgroundColor = GRAYLINECOLOR;
    [scrollView addSubview:lineView];
    
    UILabel *contactLabel = [self getLabelWith:CGRectMake(labX, infoLabel.maxY + labY*2 , labW, height) WithTitle:@"联系人" withColor:GRAYCOLOR];
    [scrollView addSubview:contactLabel];
    UILabel *phoneLabel = [self getLabelWith:CGRectMake(labX, contactLabel.maxY + labY , labW, height) WithTitle:@"联系电话" withColor:GRAYCOLOR];
    [scrollView addSubview:phoneLabel];
    UILabel *recordLabel = [self getLabelWith:CGRectMake(labX, phoneLabel.maxY + labY , labW, height) WithTitle:@"拜访记录" withColor:GRAYCOLOR];
    [scrollView addSubview:recordLabel];
    
    
    _nameTF = [self addTextFieldWithFrame:CGRectMake(tfX, contactLabel.y-labY, tfW, labH) AndStr:@"必填"];
    [scrollView addSubview:_nameTF];
    _nameTF.userInteractionEnabled = YES;
    
    _telTF = [self addTextFieldWithFrame:CGRectMake(tfX, phoneLabel.y-labY, tfW, labH) AndStr:@"必填"];
    _telTF.keyboardType = UIKeyboardTypeNumberPad;
    [scrollView addSubview:_telTF];
    _telTF.userInteractionEnabled = YES;
    
    
    _visitTV = [[UITextView alloc] initWithFrame:CGRectMake(tfX, recordLabel.y, tfW, labH*3)];
    _visitTV.font = [ViewTool getFont:15.0f];
    _visitTV.textColor = UIColorFromRGB(0x636365);
    _visitTV.layer.borderWidth = 0;
    _visitTV.contentInset = UIEdgeInsetsMake(-8.f, -5.f, -8.f, -5.f);
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 10;// 字体的行间距
    
    NSDictionary *attributes = @{
                                 NSFontAttributeName:_visitTV.font,
                                 NSParagraphStyleAttributeName:paragraphStyle
                                 };
    _visitTV.attributedText = [[NSAttributedString alloc] initWithString:@"" attributes:attributes];
    [scrollView addSubview:_visitTV];
    
    picVew = [[PictureSelectView alloc] initWithFrame:CGRectMake(tfX, _visitTV.maxY + labY, _visitTV.width, labW)];
    picVew.isHadCheck = NO;//未检查的时候显示添加按钮
    picVew.delegate =  self;
    picVew.backgroundColor = [UIColor whiteColor];
    [scrollView addSubview:picVew];
    
    UIView *line2 = [self getLineWith:CGRectMake(0, picVew.maxY + labY - 1, kScreenWidth, 1)];
    [scrollView addSubview:line2];
    
    bg.height = line2.maxY-grayH;
    
    UILabel *exampleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, line2.maxY+10, kScreenWidth - 12, 12)];
    exampleLabel.text = @"* 只支持jpg、png、gif格式图片，文件大小最大10MB";
    exampleLabel.textColor = GRAYCOLOR;
    exampleLabel.textAlignment = NSTextAlignmentRight;
    exampleLabel.font = [ViewTool getFont:13.0f];
    [scrollView addSubview:exampleLabel];
    
}

#pragma mark --点击添加照片
- (void)addImage
{
    if(picVew.allPicArray.count == 3){
        
        [Tools showMessage:@"最多选择3张照片哦" view:self];
    }else{
    if(IsIOS8Lower){
        UIActionSheet * actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"打开手机相册",@"手机相机拍摄", nil];
        [actionSheet showInView:self.view];
    }else{
        UIAlertController * alertionControll = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"打开手机相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self takePictureInPhone1];
        }];
        UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"手机相机拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self takePictureWithCamera];
        }];
        UIAlertAction * action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertionControll addAction:action1];
        [alertionControll addAction:action2];
        [alertionControll addAction:action3];
        if(alertionControll != nil){
            [self presentViewController:alertionControll animated:YES completion:nil];
        }
    }
    }
}

#pragma mark --actionSheet delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self takePictureInPhone1];
    }else if (buttonIndex == 1){
        [self takePictureWithCamera];
    }
}

- (void)actionSheetCancel:(UIActionSheet *)actionSheet
{
    [actionSheet dismissWithClickedButtonIndex:2 animated:YES];
}

- (void)takePictureInPhone1
{

    if(![Tools isAllowPhoto]){
        [Tools showMessage:@"APP无相册访问权限，请先设置!" view:self];
        return;
    }

    if (![QBImagePickerController isAccessible]) {
        [Tools showMessage:@"APP无相册访问权限，请先设置!" view:self];
    }
    QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsMultipleSelection = YES;
    if (picVew.allPicArray.count >= 3) {
        [Tools showMessage:@"最多选择3张照片哦" view:self];
        return;
    }else if (picVew.allPicArray.count == 2){
        imagePickerController.maximumNumberOfSelection = 1;
    }else if (picVew.allPicArray.count == 1){
        imagePickerController.maximumNumberOfSelection = 2;
    }else if (picVew.allPicArray.count == 0){
        imagePickerController.maximumNumberOfSelection = 3;//最大上传5张
    }
    
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:imagePickerController];
    [self presentViewController:navigationController animated:YES completion:NULL];
}
#pragma mark -- QBImage代理
- (void)imagePickerController:(QBImagePickerController *)imagePickerController didSelectAssets:(NSArray *)assets
{
    _choosePicDataArray = [NSMutableArray array];
    
    if (assets.count > 3) {
        [Tools showMessage:@"最多选择3张照片哦" view:imagePickerController];
        return;
    }
    
    [self dismissImagePickerController];
    for(int i = 0 ;i< assets.count; i ++){
        ALAssetRepresentation *resentation = [assets[i]  defaultRepresentation];
        UIImage *image = [UIImage imageWithCGImage:[resentation fullResolutionImage]];
        
        NSData *data = UIImageJPEGRepresentation(image, 0.3);
        [_choosePicDataArray addObject:data];
        
    }
    picVew.images = _choosePicDataArray;
    if (picVew.allPicArray.count > 3) {
        [Tools showMessage:@"最多选择3张照片哦" view:self];
    }
    if (picVew.allPicArray.count >= 3) {
        picVew.isHideBtn = YES;
    }
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)dismissImagePickerController
{
    if (self.presentedViewController) {
        [self dismissViewControllerAnimated:YES completion:NULL];
    }
}

- (void)imagePickerControllerDidCancel1:(QBImagePickerController *)imagePickerController
{
    [self dismissImagePickerController];
}

- (void)takePictureWithCamera
{
    if(![Tools isAllowTakePhoto]){
        [Tools showMessage:@"APP无相机访问权限，请先设置!" view:self];
        return;
    }    
    CameraViewController *cameraVC = [[CameraViewController alloc] init];
    cameraVC.isShouldBack = YES;//这个是要拍完照 返回
    cameraVC.isHaveRuleBtn = YES;
    [self presentViewController:cameraVC animated:YES completion:nil];
    cameraVC.backBlock = ^(NSData *data,NSData *data1){
        _cameraPicArray = [NSMutableArray array];
        if(picVew.allPicArray.count >= 2){
            picVew.isHideBtn = YES;
        }
        if (picVew.allPicArray.count < 4) {
            [_cameraPicArray addObject:data];
        }else{
            [Tools showMessage:@"最多选择3张哦" view:self];
        }
        picVew.images = _cameraPicArray;
    };
}

#pragma mark - Action Handle

- (void)configLocationManager
{
    self.locationManager = [[AMapLocationManager alloc] init];
    
    [self.locationManager setDelegate:self];
    
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    
    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    
    [self.locationManager setAllowsBackgroundLocationUpdates:NO];
    
    [self.locationManager setLocationTimeout:LocationTimeout];
    
    [self.locationManager setReGeocodeTimeout:ReGeocodeTimeout];
    
}
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
}
- (void)cleanUpAction
{
    [self.locationManager stopUpdatingLocation];
    
    [self.locationManager setDelegate:nil];
}

- (void)reGeocodeAction
{
//    [self.locationManager startUpdatingLocation];
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:self.completionBlock];
}

#pragma mark - Initialization

- (void)initCompleteBlock
{
    __weak AddRecordViewController *wSelf = self;
    self.completionBlock = ^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error){
        NSLog(@"initCompleteBlock");
        if (location){
            NSLog(@"%@",[NSString stringWithFormat:@"%@ \n %@-%@-%.2fm", regeocode.formattedAddress,regeocode.citycode, regeocode.adcode, location.horizontalAccuracy]);
            NSLog(@"%@",[NSString stringWithFormat:@"lat:%f;lon:%f \n accuracy:%.2fm", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy]);
            if (regeocode.formattedAddress != nil && regeocode.formattedAddress.length > 0) {
                gps_address = regeocode.formattedAddress;
            }
            gps = [NSString stringWithFormat:@"%f,%f",location.coordinate.longitude,location.coordinate.latitude];
            
            
            
        }
//            if (error){
//            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
//            [SVProgressHUD dismiss];
//            wSelf.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:wSelf action:@selector(commitClick:)];
//            NSLog(@"error:%@",error);
//            [Tools showMessage:@"定位失败" view:wSelf];
//        }
        [wSelf uploadImages];
        [wSelf cleanUpAction];
    };
}


- (UIImageView *)imageWith:(CGRect)frame withName:(NSString *)str{
    UIImageView *img = [[UIImageView alloc]initWithFrame:frame];
    img.image = [UIImage imageNamed:str];
    return img;
}
- (UILabel *)getLabelWith:(CGRect)frame WithTitle:(NSString *)title withColor:(UIColor *)color
{
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.text = title;
    label.textColor = color;
    label.textAlignment = NSTextAlignmentLeft;
    label.font = [ViewTool getFont:15.0f];
    return label;
}
-(UIView *)getLineWith:(CGRect)frame
{
    UIView *view = [[UIView alloc] initWithFrame:frame];
    view.backgroundColor = UIColorFromRGB(0xe8e7ec);
    return view;
}

-(UITextField *)addTextFieldWithFrame:(CGRect)frame AndStr:(NSString *)placeholder
{
    UITextField *textF=[[UITextField alloc]initWithFrame:frame];
    textF.textColor = UIColorFromRGB(0x646368);
    textF.placeholder=placeholder;
    [textF setValue:UIColorFromRGB(0xe5e5e5) forKeyPath:@"_placeholderLabel.textColor"];
    textF.font = [ViewTool getFont:15.0f];
    [textF setValue:[ViewTool getFont:15.0f] forKeyPath:@"_placeholderLabel.font"];
    return textF;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
